<template>
  <div class="h100 strategyPage tablePageWarp">
    <div class="strategySearch table-page-search-wrapper">
      <strategy-search :version-type="versionType" v-model="queryParams"
                       @change="$nextTick(()=>searchData(true))"
                       :upgrade-trigger-type="upgradeTriggerType"
                       @clickbtn="handleClickSearchBtn"></strategy-search>
    </div>
    <div style="" v-if="versionType !== 'develop'">
      <a-radio-group buttonStyle="solid" v-model="queryParams.fromGcy" style="float:right;margin-bottom: 8px" @change="searchData(true)">
        <a-radio-button :value="false">
          规划院
        </a-radio-button>
        <a-radio-button :value="true">
          工程院
        </a-radio-button>
      </a-radio-group>
    </div>
    <div class="strategyMain">
      <strategy-table-list :version-type="versionType"
                           :upgrade-trigger-type="upgradeTriggerType" :queryParams="queryParams"
                           @clickbtn="handleMainCompClick" ref="strategyTableList"></strategy-table-list>
    </div>
    <!-- 发布策略弹框 -->
    <publish-update-strategy
      ref="publishUpdateStrategyRef"
      @published="handlePublished"
      :version-type="versionType"
      :upgrade-trigger-type="upgradeTriggerType"
      :strategy-id="strategyId"
      :conditionStrategyId="conditionStrategyId"
      :task-id="defaultSelectedTaskId">
    </publish-update-strategy>
  </div>
</template>
<script>
import StrategySearch from './components/StrategySearch.vue'
import StrategyTableList from './components/StrategyTableList.vue'
import EditStrategy from './components/EditStrategy'
import StrategyDetail from './components/StrategyDetail'
import PublishUpdateStrategy from './components/PublishUpdateStrategy'
import EditTestForm from './components/EditTestForm.vue'
import LookupTestForm from './components/LookupTestForm.vue'
import { minxinDrawerUse } from '@/utils/mixin'
import lodash from 'lodash'
import { strategyInitFormData } from './config/form'
import { strategyPerms } from '@/config/permission/index'
import StrategyJs from '../strategy'
import taskApi from "@api/modules/task";
import EditChannelTest from "@views/strategy/FotaUpdate/components/EditChannelTest";

export default {
  mixins: [minxinDrawerUse],
  components: {
    StrategySearch,
    StrategyTableList,
    EditStrategy,
    PublishUpdateStrategy,
    EditTestForm,
    EditChannelTest,
    LookupTestForm
  },
  provide() {
    return {
      queryParams: this.queryParams
    }
  },
  data () {
    return {
      queryParams : {
        type: 1,
        name: '',
        createBy: undefined,
        vehicleVersionId: undefined,
        fromGcy: false
      },
      nowTime: 123456,
      spinningLoading: false,
      operationTip: '',
      // 当前策略Id
      strategyId: '',
      // 条件策略id
      conditionStrategyId: '',
      versionType : StrategyJs.getTypeFromPath(this.$route.path, 1, this),
      upgradeTriggerType :'USER',
      // 默认选中的测试任务id
      defaultSelectedTaskId: ''
    }
  },
  computed: {
    // versionType(){
    //   return StrategyJs.getTypeFromPath(this.$route.path, 1, this)
    // },
    // upgradeTriggerType(){
    //   return StrategyJs.getTypeFromPath(this.$route.path, 2, this)
    // },
  },
  created () {
  },
  methods: {
    handleMainCompClick (obj) {
      if (this[obj.type]) {
        this[obj.type](obj.data)
      }
    },
    handleClickSearchBtn (data) {
      this.nowTime = new Date().getTime()
      if (this[data.type]) {
        this[data.type]()
      }
    },
    // 添加FOTA升级策略
    addStrategy () {
      const name = this.$t('sjcl')
      const vars = {
        editRecord: {
          ...lodash.cloneDeep(strategyInitFormData),
          name: `${name}[${this.$commonFun.getDateMinuteStr(new Date())}]`
        },
        class: 'rightDrawerWithoutCol',
        versionType:this.versionType,
        time: Date.now()
      }
      const buttons = this.getSjclDrawerButtons(strategyPerms[this.versionType][this.upgradeTriggerType].fotaSjcl.add)
      const title = this.$t('new') + StrategyJs.getTestTypeDesc(this.versionType) + name
      this.showRightDrawerNoReset(EditStrategy, title, buttons, 'large', vars)
    },
    // 编辑FOTA升级策略
    editStrategy (record, isCopy) {
      const vars = {
        versionType:this.versionType,
        upgradeTriggerType: record.versionType,
        time: Date.now(),
        id: record.id,
        isCopy,
        class: 'rightDrawerWithoutCol'
      }
      const buttons = this.getSjclDrawerButtons(isCopy ?strategyPerms[this.versionType][this.upgradeTriggerType].fotaSjcl.copy:strategyPerms[this.versionType][this.upgradeTriggerType].fotaSjcl.edit)
      const title = this.$t(isCopy ? 'copy' : 'edit') + this.$t('sjcl')
      this.showRightDrawer(EditStrategy, title, buttons, 'large', vars)
    },
    // 复制策略
    copyStrategy (data) {
      this.editStrategy(data, true)
    },
    // 获取编辑，新建升级策略时右侧弹框按钮
    getSjclDrawerButtons (auth) {
      const _this = this
      return this.getRightDrawerFooterButtons({
        key: auth,
        method: 'saveEditStrategyFormData',
        callback (data) {
          _this.searchData(!data.id)
        }
      })
    },
    // 保存升级策略表单
    saveEditStrategyFormData (data) {
      if (data.id === 'copy') {
        // eslint-disable-next-line no-param-reassign
        data.id = null
      }
      const method = data.id ? 'editStrategyData' : 'addStrategyData'
      return this.$store.dispatch(method, data)
    },
    // 查看策略详情
    lookupRowDetail (data) {
      const vars = {
        id: data.id,
        versionType: this.versionType,
        upgradeTriggerType: this.upgradeTriggerType,
        time: Date.now()
      }
      this.showRightDrawer(StrategyDetail, data.name, [], 'large', vars)
    },
    // 发布策略
    publishStrategy (record, defaultSelectedTaskId = '') {
      this.strategyId = record.id
      this.conditionStrategyId = record.conditionStrategyId
      this.defaultSelectedTaskId = defaultSelectedTaskId
      this.$refs.publishUpdateStrategyRef.switchVisible(true)
    },
    // 通过行列表申请发布还有就是在查看测试处申请发布
    handlePublished () {
      this.removeRightDrawer()
      this.searchData(false)
    },
    // 新建测试
    createTest (record) {
      const _this = this
      // 任务类型9表示fata测试任务
      const type = undefined
      const vars = {
        editRecord: {
          strategyId: record.id,
          modelId: record.modelId,
          type,
          vehicleVersionId: record.vehicleVersionId,
          name: `${this.$t('strategyTestTask')}[${this.$commonFun.getDateMinuteStr(new Date())}]`
        },
        testType:this.versionType,
        upgradeTriggerType:this.upgradeTriggerType,
        time: Date.now()
      }
      const auth = strategyPerms[this.versionType][this.upgradeTriggerType].fotaSjcl.createTest
      const buttons = this.getRightDrawerFooterButtons({
        key: auth,
        method: 'saveEditTestFormData',
        callback () {
          _this.searchData(false)
        }
      })
      this.showRightDrawer(EditChannelTest, this.$t('new') + this.$t('test'), buttons, 'huge', vars)
    },
    // 查看测试弹框
    lookupTest (record) {
      const _this = this
      const type = 9
      const vars = {
        strategyId: record.id,
        type,
        versionType:this.versionType,
        upgradeTriggerType:this.upgradeTriggerType,
        time: Date.now()
      }
      //  是升级策略时状态为未被停用且测试中才能使用申请发布按钮
      let buttons = []
      if (record.enabled && record.status === 2) {
        // 查看测试中申请发布按钮
        // 测试任务不允许发布
        if (this.versionType === 'PROD') {
          buttons = [{
            key: strategyPerms[this.versionType][this.upgradeTriggerType].fotaSjcl.publish,
            title: 'publishPolicy',
            type: 'primary',
            name: 'publishBtn',
            method (comp) {
              _this.publishStrategy({ id: comp.strategyId }, comp.selectedTaskId)
            },
            loading: false,
            disabled: false
          }, {
            key: '',
            title: 'cancel',
            type: 'info',
            name: 'cancelBtn',
            method: null,
            callback: null,
            loading: false,
            disabled: false
          }];
        }
      }
      this.$store.commit('resetStrategyTaskVehicleQueryParams')
      this.showRightDrawer(LookupTestForm, this.$t('view') + this.$t('test'), buttons, 'huge', vars)
    },
    // 保存新建测试数据
    saveEditTestFormData(data) {
      return taskApi.addTestTaskData(data, this.versionType)
    },
    // 批量删除
    deleteList (record) {
      const vm = this
      this.confirmAjax({
        content: this.$t('deleteConfirmNotice').replace('__CONTENT__', `${this.$t('strategy')}[${record.name}]`),
        title: vm.$t('delete') + vm.$t('strategy'),
        loadingTip: `${vm.$t('delete')}[${record.name}]`,
        method: 'deleteStrategyData',
        data: { ids: [record.id], enabled: false, versionType: this.versionType, upgradeTriggerType:this.upgradeTriggerType }
      })
    },
    // 停用策略
    disabledStrategy (record) {
      const vm = this
      this.confirmAjax({
        content: vm.$t('disabledConfirmNotice').replace('__CONTENT__', `${vm.$t('strategy')}[${record.name}]?`),
        title: vm.$t('disabled') + vm.$t('strategy'),
        loadingTip: `${vm.$t('disabled')}[${record.name}]`,
        method: 'disabledStrategyData',
        data: { ids: [record.id], enabled: false, versionType: this.versionType, upgradeTriggerType:this.upgradeTriggerType }
      })
    },
    // 启用策略
    enabledStrategy (record) {
      const vm = this
      this.confirmAjax({
        content: vm.$t('enabledConfirmNotice').replace('__CONTENT__', `${vm.$t('strategy')}[${record.name}]?`),
        title: vm.$t('start') + vm.$t('strategy'),
        loadingTip: `${vm.$t('start')}[${record.name}]`,
        method: 'disabledStrategyData',
        data: { ids: [record.id], enabled: true, versionType: this.versionType, upgradeTriggerType:this.upgradeTriggerType }
      })
    },
    changeOperationTip (newCont, oldCont = '__CONTENT__') {
      this.operationTip = this.operationTip.replace(oldCont, newCont)
    },
    confirmAjax (obj = { title: '', content: '', loadingTip: '', method: '', data: null, callback: null }) {
      if (this.spinningLoading) {
        return
      }
      const vm = this
      const { content } = obj
      vm.$confirm({
        title: obj.title,
        content,
        class: 'confirmStyle',
        width: 378,
        onOk () {
          vm.spinningLoading = true
          const newCont = obj.loadingTip
          vm.changeOperationTip(newCont)
          vm.$store.dispatch(obj.method, obj.data).then(() => {
            if (obj.callback) {
              obj.callback()
              return
            }
            vm.$message.success(obj.title + vm.$t(200))
            vm.searchData(false)
          }).finally(() => {
            vm.changeOperationTip('__CONTENT__', newCont)
            vm.spinningLoading = false
          })
        },
        onCancel () { }
      })
    },
    searchData (isPageOne = true) {
      this.$refs.strategyTableList.refreshData(isPageOne)
    }
  }
}
</script>
<style scoped lang="less">
@import url('../style/list.less');
</style>
